<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Admin/classes/PhpFox_ComponentMusicModUpdate.class.php, $Author:  $ */



/** Component for showing site content items and editing them
 *
 * @version $Id: PhpFox_ComponentMusicModUpdate.class.php 46 2007-12-14 23:12:21Z phpfoxsv $
 * @package module.admin
 */
class PhpFox_Mod_Admin_ComponentMusicModUpdate extends BaseComponent
{		
	function _isTable($sTable)		
	{
		return $this->oDatabase->getRows("SHOW TABLES LIKE '". $sTable ."'");	
	}

    function process()
    {
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oMusicService = App::getModuleService('Music', 'Music');
        /* @var $oMusicService PhpFox_Mod_Music_ServiceMusic */
        $oSongItem = App::getModuleItem('Music', 'Song');
        /* @var $oSongItem PhpFox_Mod_Music_ItemSong */
        $oMusicianItem = App::getModuleItem('Music', 'Musician');
        /* @var $oMusicianItem PhpFox_Mod_Music_ItemMusician */

        $oTpl = &$this->_oModule->getTemplate();
        $oReq = &App::getRequest();
        App::loadClass('Database');
        $oDb = Database::get();
		$oSrvVideo =& App::getModuleService('Video', 'Video');
		$sCmd = $oReq->get('cmd');
		
		$aPluginTotals = array();
       	$aPluginTotals['mp3_songs'] = ($this->_isTable('phpfox_media') ? $oDb->getField("SELECT COUNT(*) FROM phpfox_media " . ($this->_checkField('phpfox_media', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
		$aPluginTotals['music_videos'] = ($this->_isTable('music') ? $oDb->getField("SELECT COUNT(*) FROM music " . ($this->_checkField('music', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
		$aPluginTotals['videos'] = ($this->_isTable('php_videos') ? $oDb->getField("SELECT COUNT(*) FROM php_videos " . ($this->_checkField('php_videos', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
		$aPluginTotals['editor'] = ($this->_isTable('phpfox_editor') ? $oDb->getField("SELECT COUNT(*) FROM phpfox_editor " . ($this->_checkField('phpfox_editor', 'is_imported') ? " WHERE is_imported != 1" : "")) : 0);
		$aPluginTotals['total'] = ($aPluginTotals['mp3_songs'] + $aPluginTotals['music_videos'] + $aPluginTotals['videos'] + $aPluginTotals['editor']);
		$oTpl->assign('aTotal', $aPluginTotals);

		switch($sCmd)
		{
			case 'import-mp3':
			
				if (!$this->_checkField('phpfox_media', 'is_imported'))
				{
					$oDb->query("ALTER TABLE `phpfox_media` ADD `is_imported` TINYINT( 1 ) UNSIGNED NOT NULL");
					$oDb->query("ALTER TABLE `phpfox_media` ADD INDEX ( `is_imported` )");
				}
			
            	$aSongs = $oDb->selectRows(App::getParam('plugin.mp3.tablename'));

				$iTotal = 0;
            	for ($i = 0; $i < count($aSongs); $i++)
            	{
            	    $iUserId     = $oSecurityService->getUserIdByName($aSongs[$i]['user']);
            	    $sSourceFile = App::getParam('plugin.mp3.filepath') . $aSongs[$i]['id'] . '.mp3';
            	    if (!$iUserId)
            	    {
            	        $iUserId = App::getUser('id');
            	    }
            	    if ($iUserId && $oMusicService->_checkSongFormat($sSourceFile))
            	    {
            	    	$iTotal++;
            	        $iMusicianId = $oMusicService->addMusician($aSongs[$i]['name']);
	
	                	$aAlbumData = array
	                	(
	                    	'album_title'       => htmlspecialchars($aSongs[$i]['title']),
	                    	'musician_name'     => htmlspecialchars($aSongs[$i]['name']),
	                    	'album_year'        => '2007',
	                    	'genre_id'          => 1
	                	);
	
	                	$iAlbumId = $oMusicService->addAlbum($aAlbumData, $iUserId);
	
	                    $oSongItem->aData['user_id']          = $iUserId;
	                    $oSongItem->aData['musician_id']      = $iMusicianId;
	                    $oSongItem->aData['album_id']      = $iAlbumId;
	                    $oSongItem->aData['song_title']       = $oDb->escape($aSongs[$i]['title']);
	                    $oSongItem->aData['song_cdate']       = date('Y-m-d H:i:s', $aSongs[$i]['time']);
	                    $oSongItem->aData['song_is_approved'] = ($aSongs[$i]['approve'] == 1 ? 0 : 1);
	
	                    $iSongId = $oSongItem->insert();
	                    unset($oSongItem->aData);
		
	                    $sDestinFile = App::getParam('music.path') . $iSongId . '.mp3';
	
	                    rename($sSourceFile, $sDestinFile);
	                }
					$oDb->update('phpfox_media', array('is_imported' => 1), "id = '" . $aSongs[$i]['id'] . "'");
	            }
	
	            App::gotoUrl('admin.extra.musicmod-update', array(), App::format('Mod_Admin.import_mp3', $iTotal));
        
        		break;
        		
        	case 'import-videos':
        	
        		$aCnt = array('flv' => 0, 'normal' => 0, 'failed' => 0, 'comments' => 0, 'listing' => 0);
        	
				if (!$this->_checkField('php_videos_list', 'is_imported'))
				{
					$oDb->query("ALTER TABLE `php_videos_list` ADD `is_imported` TINYINT( 1 ) UNSIGNED NOT NULL");
				}
        	
        		$aRows = $oDb->getRows("
        			SELECT
						*
					FROM php_videos_list
					WHERE is_imported != 1
        		");

				$aListId = array();
        		foreach($aRows as $aRow)
        		{
        			$aCheck = $oDb->getRow("SELECT list_id FROM " . App::getT('videos_list') . " WHERE list_name = '" . $oDb->escape($aRow['list_name']) . "'");
        			$iId = (isset($aCheck['list_id']) ? $aCheck['list_id'] : $oDb->insert(App::getT('videos_list'), array('list_name' => $aRow['list_name'], 'list_total' => $aRow['list_total'])));
        			$aListId[$aRow['list_id']] = $iId;
        			$aCnt['listing']++;
        			$oDb->update('php_videos_list', array('is_imported' => 1), "list_id = '" . $aRow['list_id'] . "'");
        		}
        		
				if (!$this->_checkField('php_videos', 'is_imported'))
				{
					$oDb->query("ALTER TABLE `php_videos` ADD `is_imported` TINYINT( 1 ) UNSIGNED NOT NULL");
				}

        		$aRows = $oDb->getRows("
        			SELECT
						*
					FROM php_videos
					WHERE is_imported != 1
        		");

        		$sVidPath = App::getParam('path') . 'file/videos/src/';
        		$sImagePath = App::getParam('path') . 'file/videos/image/';

				$aNewVidId = array();
        		foreach($aRows as $aRow)
        		{
        			$iVidId = $aRow['vid_id'];
        			unset($aRow['vid_id']);
					$aRow['vid_list_id'] = $aListId[$aRow['vid_list_id']];
					
        			if (file_exists($sVidPath . $iVidId . '.flv'))
        			{
        				$aCnt['flv']++;
        				$aRow['vid_type'] = 'flv';
        				$iId = $oSrvVideo->addVideo($aRow);
        				$aNewVidId[$iVidId] = $iId;
        				rename($sVidPath . $iVidId . '.' . $aRow['vid_type'], $sVidPath . $iId . '.' . $aRow['vid_type']);
        				if (file_exists($sImagePath . $iVidId . '.jpg'))
        				{
        					rename($sImagePath . $iVidId . '.jpg', $sImagePath . $iId . '.jpg');
        				}
        			}
        			else if (file_exists($sVidPath . $iVidId . '.' .$aRow['vid_type']))
        			{
        				$aCnt['normal']++;
        				$iId = $oSrvVideo->addPendingVideo($aRow);
        				rename($sVidPath . $iVidId . '.' .$aRow['vid_type'], $sVidPath . 'pending_' . $iId . '.' . $aRow['vid_type']);
        				if (file_exists($sImagePath . $iVidId . '.jpg'))
        				{
        					rename($sImagePath . $iVidId . '.jpg', $sImagePath . 'pending_' . $iId . '.jpg');
        				}
        			}
        			else
        			{
        				$aCnt['failed']++;
        			}
        			
        			$oDb->update('php_videos', array('is_imported' => 1), "vid_id = '" . $iVidId . "'");
        		}

				if (!$this->_checkField('php_videos_comments', 'is_imported'))
				{
					$oDb->query("ALTER TABLE `php_videos_comments` ADD `is_imported` TINYINT( 1 ) UNSIGNED NOT NULL");
				}

        		$aRows = $oDb->getRows("
        			SELECT
						*
					FROM php_videos_comments
					WHERE is_imported != 1
        		");

	       		foreach($aRows as $aRow)
        		{
        			if (!isset($aNewVidId[$aRow['cm_mainid']]))
        			{
        				continue;
        			}
        			$iVidId = $aRow['cm_id'];
        			unset($aRow['cm_id']);
        			$aRow['cm_mainid'] = $aNewVidId[$aRow['cm_mainid']];
					$aCnt['comments']++;
        			$oDb->insert(App::getT('videos_comments'), $aRow);
        			$oDb->update('php_videos_comments', array('is_imported' => 1), "vid_id = '" . $iVidId . "'");
        		}
				
				App::gotoUrl('admin.extra.musicmod-update', array(), App::format('Mod_Admin.import_videos', array($aCnt['flv'], $aCnt['normal'], $aCnt['comments'], $aCnt['listing'])));
        	
        		break;
        		
        	case 'import-music-videos':
        	
				if (!$this->_checkField('music', 'is_imported'))
				{
					$oDb->query("ALTER TABLE `music` ADD `is_imported` TINYINT( 1 ) UNSIGNED NOT NULL");
				}
       	
        		$aRows = $oDb->getRows("
        			SELECT 
        				*
        			FROM music
        			WHERE is_imported != 1
        		");
        		
        		$iTotal = 0;
        		foreach($aRows as $aRow)
        		{
        			$aCode = explode("SRC=", $aRow['code']);
        			if (!isset($aCode[1]))
        			{
        				$aCode = explode("src=", $aRow['code']);
        			}
       			
        			if (isset($aCode[1]))
        			{
	        			if (substr($aCode[1], 0, 1) == '"')
	        			{
	        				$aCode1 = explode("\"", $aCode[1]);
	        			}
	        			else
	        			{
	        				$aCode1 = explode("'", $aCode[1]);
	        			}

	        			if (isset($aCode1[1]) && substr($aCode1[1], 0, 4) == 'http' 
	        				&& (
	        					eregi('google.', $aCode1[1])
	        					|| eregi('ifilm.', $aCode1[1])
	        					|| eregi('youtube.', $aCode1[1])
	        				)
	        			)
	        			{
	        				if (eregi('youtube.', $aCode1[1]))
	        				{
	        					$iStreamId = 1;
	        				}
	        				else if (eregi('ifilm.', $aCode1[1]))
	        				{
	        					$iStreamId = 7;
	        				}
	        				else
	        				{
	        					$iStreamId = 2;
	        				}

	        				$aData = array
	        				(
								'vid_list_id' => 1,
								'vid_title' => $aRow['title'],
								'vid_time' => time(),
								'vid_total' => $aRow['views'],
								'vid_url' => $aCode1[1],
								'stream_id' => $iStreamId,
								'featured' => $aRow['feature']
	        				);
	        				
	        				$iTotal++;
	        				$oSrvVideo->addVideo($aData);
	        			}
					}
					
     				$oDb->update('music', array('is_imported' => 1), "musicid = '" . $aRow['musicid'] . "'");
        		}
        		
        		App::gotoUrl('admin.extra.musicmod-update', array(), App::format('Mod_Admin.import_music_videos', $iTotal));
        	
        		break;
        		
        	case 'import-editor':
        		
				if (!$this->_checkField('phpfox_editor', 'is_imported'))
				{
					$oDb->query("ALTER TABLE `phpfox_editor` ADD `is_imported` TINYINT( 1 ) UNSIGNED NOT NULL");
				}
				
				$oSrvPage =& App::getModuleService('Site', 'Page');
				        		
        		$aRows = $oDb->getRows("
        			SELECT 
        				*
        			FROM phpfox_editor
        			WHERE is_imported != 1
        		");
        		
        		$iTotal = 0;
        		foreach ($aRows as $aRow) 
        		{
        			$iTotal++;        		
        			$aData = array();
        			$aData['title_head'] = $aRow['title'];
					$aData['title_menu'] = $aRow['title'];
					$aData['title_url'] = $aRow['title'];
					$aData['content'] = $aRow['text'];
					$aData['user_id'] = App::getUser('id');
					$aData['meta'] = '';        			
        			$oSrvPage->_add($aData);
        			$oDb->update('phpfox_editor', array('is_imported' => 1), "id = '" . $aRow['id'] . "'");
        		}
        		
        		App::gotoUrl('admin.extra.musicmod-update', array(), App::format('Mod_Admin.imported_pages', $iTotal));
        		
        		break;
        }

        return $oTpl->fetch('MusicModUpdate.html');
    }
    
    function _checkField($sTable, $sVar)
    {
    	$aCheckOptions = $this->oDatabase->getRows("SHOW COLUMNS FROM `" . $sTable . "`");
		foreach($aCheckOptions as $aLangOption)
		{
			if ( $aLangOption['Field'] == $sVar )
			{
				return true;
			}
		}
		return false;
    }
}
?>